package com.itheima.security;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @authou: fu
 * @date:Created in 2019/12/10
 * @description:
 * @version:1.0
 */
@Component
public class SecurityUserService implements UserDetailsService {

    @Reference
    private UserService userService;

    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if (StringUtils.isEmpty(username)){
            return null;
        }
        //获取用户表数据
        User user = userService.findByUserName(username);
        if (user == null){
            return null;
        }
        //获取角色信息和权限信息.存入到list集合中
        List<GrantedAuthority> list = new ArrayList<>();
        Set<Role> roles = user.getRoles();
        if (roles!=null && roles.size()>0){
            for (Role role : roles) {
                //授予角色
                list.add(new SimpleGrantedAuthority(role.getKeyword()));
                Set<Permission> permissions = role.getPermissions();
                if (permissions != null && permissions.size()>0){
                    for (Permission permission : permissions) {
                        //授予权限
                        list.add(new SimpleGrantedAuthority(permission.getKeyword()));
                    }
                }
            }
        }


        return new org.springframework.security.core.userdetails.User(username,user.getPassword(),list);
    }
}
